package com.letao.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.letao.server.dto.ReadListDTO;
import com.letao.server.dto.Result;
import com.letao.server.dto.UserMessageDTO;
import com.letao.server.entity.MessageInfo;
import com.letao.server.entity.UserInfo;
import com.letao.server.mapper.MessageInfoMapper;
import com.letao.server.mapper.UserInfoMapper;
import com.letao.server.service.IMessageService;
import com.letao.server.service.IUserService;
import com.letao.server.utils.UserHolderUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
@Slf4j
public class MessageServiceImpl extends ServiceImpl<MessageInfoMapper, MessageInfo> implements IMessageService {
    @Resource
    private MessageInfoMapper mapper;

    @Resource
    private IUserService userService;

    @Resource
    private UserInfoMapper userInfoMapper;

    /**
     * 用户查询聊天信息
     *
     * @param page 页码
     * @return 返回的结果
     */
    @Override
    public Result queryUser(Long page) {
        Long id = UserHolderUtils.getUser().getId();
        IPage<MessageInfo> ipage = new Page<>(page, 30);
        QueryWrapper<MessageInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", id);
        wrapper.orderByDesc("create_time");
        IPage<MessageInfo> messageInfoIPage = mapper.selectPage(ipage, wrapper);
        List<MessageInfo> records = messageInfoIPage.getRecords();
        for (MessageInfo record : records) {
            if (record.getMsgType() == 1) {
                record.setIsUnread(0);
                mapper.updateById(record);
            }
        }
        Collections.reverse(records);
        return Result.success(records);
    }

    /**
     * 管理员查询未读用户列表
     *
     * @return 返回的结果
     */
    @Override
    public Result queryList() {
        QueryWrapper<MessageInfo> wrapper = new QueryWrapper<>();
        wrapper.select("sum(if(msg_type=0,is_unread,0)) as unread, user_id as userId")
                .groupBy("user_id")
                .last("limit 30");
//                .orderByDesc("create_time");
        List<Map<String, Object>> maps = mapper.selectMaps(wrapper);
        log.debug("{}", maps);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM-dd HH:mm ss");
        for (Map<String, Object> map : maps) {
            UserInfo user = userService.getById((Serializable) map.get("userId"));
            map.put("userName", user.getAccount());
            map.put("userImage", user.getUserImage());
            MessageInfo messageInfo = query().eq("user_id", user.getId()).orderByDesc("create_time").list().get(0);
            map.put("latest_msg", messageInfo.getContent());
            map.put("latest_time", messageInfo.getCreateTime().format(formatter));
        }
        maps.sort(new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                int n1 = Integer.parseInt(String.valueOf(o1.get("unread")));
                int n2 = Integer.parseInt(String.valueOf(o2.get("unread")));
                LocalDateTime t1 = LocalDateTime.parse(String.valueOf(o1.get("latest_time")), formatter);
                LocalDateTime t2 = LocalDateTime.parse(String.valueOf(o2.get("latest_time")), formatter);
                if (n1 > 0 && n2 > 0) {
                    long offset = t1.toEpochSecond(ZoneOffset.UTC) - t2.toEpochSecond(ZoneOffset.UTC);
                    if (offset > 0) return -1;
                    if (offset == 0) return 0;
                    return 1;
                }
                if (n1 == 0 && n2 == 0) {
                    long offset = t1.toEpochSecond(ZoneOffset.UTC) - t2.toEpochSecond(ZoneOffset.UTC);
                    if (offset > 0) return -1;
                    if (offset == 0) return 0;
                    return 1;
                }

                if (n1 > 0 && n2 == 0) return -1;
                if (n1 == 0 && n2 > 0) return 1;
                return 0;
            }
        });
        String today = LocalDateTime.now().format(formatter).split(" ")[1];
        for (Map<String, Object> map : maps) {
            String data;
            String[] split = String.valueOf(map.get("latest_time")).split(" ");
            if (today.equals(split[1])) {
                data = split[2];
            } else {
                data = split[1];
            }
            map.put("latest_time", data);
        }
        return Result.success(maps);
    }

    /**
     * 管理员查询某用户聊天记录
     *
     * @param userId 用户的Id
     * @param page   页码
     * @return 返回的结果
     */
    @Override
    public Result queryDetail(Long userId, Long page) {
        QueryWrapper<MessageInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).orderByDesc("create_time");
        IPage<MessageInfo> ipage = new Page<>(page, 30);
        IPage<MessageInfo> messageInfoIPage = mapper.selectPage(ipage, wrapper);
        List<MessageInfo> records = messageInfoIPage.getRecords();
        Collections.reverse(records);
        List<UserMessageDTO> ulist = new ArrayList<>();
        for (MessageInfo record : records) {
            if (record.getMsgType() == 0) {
                record.setIsUnread(0);
                updateById(record);
            }
            UserMessageDTO dto = new UserMessageDTO(record);
            ulist.add(dto);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("rows", ulist);
        UserInfo userInfo = userInfoMapper.selectById(userId);
        map.put("userName", userInfo.getAccount());
        map.put("userImage", userInfo.getUserImage());
        map.put("userId", userId);
        return Result.success(map);
    }

    /**
     * 用户批量阅读
     *
     * @param readList 阅读的id列表
     * @return 返回的结果
     */
    @Override
    public Result readUser(ReadListDTO readList) {
        Long userId = UserHolderUtils.getUser().getId();
        for (Integer id : readList.getReadList()) {
            MessageInfo message = getById(id);
            if (message != null) {
                if (userId.equals(message.getUserId()) && message.getMsgType() == 0) {
                    message.setIsUnread(1);
                    updateById(message);
                }
            }
        }
        return Result.success();
    }

    /**
     * 管理员批量阅读
     *
     * @param readList 阅读Id列表
     * @return 返回的结果
     */
    @Override
    public Result readAdmin(ReadListDTO readList) {
        for (Integer id : readList.getReadList()) {
            MessageInfo message = getById(id);
            if (message != null) {
                if (message.getMsgType() == 1) {
                    message.setIsUnread(1);
                    updateById(message);
                }
            }
        }
        return null;
    }
}
